﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Data.Model;
using Newtonsoft.Json;
using NHibernate;
using NHibernate.Criterion;
using ZLCMS.Business.Tree;
using ZLCMS.Business;
using ZLCMS.Business.Util;

namespace ZLCMS.Web.SystemManage.Basics.Control.ddt
{
    public partial class TreeData_Category : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string _userAccount;//用户
            string _kind = Request["kind"] == null ? "" : Request["kind"];

            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                _userAccount = UserKit.GetUserAccountFailLogin();

                ICriteria crt = session.CreateCriteria<ShopCategory>().Add(Expression.Eq("OwnerAccount", _userAccount));

                if (!String.IsNullOrEmpty(Request["RootNode"]))//
                {
                    crt.Add(Expression.Gt("ParentId", 0));
                }
                if (!String.IsNullOrEmpty(_kind))//
                {
                    crt.Add(Expression.Eq("Kind", _kind));
                }

                IList<ShopCategory> list = crt.AddOrder(Order.Asc("Sort")).List<ShopCategory>();

                if (list.Count == 0 && String.IsNullOrEmpty(Request["RootNode"]))
                {
                    ShopCategory newNode = new ShopCategory();
                    newNode.CategoryName = "产品分类";
                    newNode.ParentId = 0;
                    newNode.Depth = 0;
                    newNode.Sort = 999;
                    newNode.IsActive = "1";
                    newNode.IsHot = "0";
                    newNode.Kind = _kind;
                    newNode.OwnerAccount = _userAccount;

                    session.Save(newNode);

                    newNode.Prefix = "_" + newNode.Id.ToString() + "_";

                    session.Flush();

                    list.Add(newNode);
                }

                List<ZTreeDataType> ztreeList = new List<ZTreeDataType>();

                foreach (ShopCategory item in list)
                {
                    ztreeList.Add(new ZTreeDataType() { Id = item.Id, ParentId = item.ParentId, Name = item.CategoryName });
                }

                Response.Write(JsonConvert.SerializeObject(ztreeList));
                Response.End();
            }
        }
    }
}
